<%#
 Copyright 2013-2025 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      https://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
import SockJS from 'sockjs-client';

import Stomp from 'webstomp-client';
import { Observable } from 'rxjs';
<%_ if (!authenticationTypeSession) { _%>
import { Storage } from 'react-jhipster';
<%_ } _%>

import { websocketActivityMessage } from 'app/modules/administration/administration.reducer';
import { getAccount<% if (authenticationTypeJwt) { %>, logoutSession<% } else { %>,logoutServer<% } %> } from 'app/shared/reducers/authentication';
<%_ if (authenticationTypeSession) { _%>
import cookie from 'app/shared/util/cookie-utils';
<%_ } _%>

let stompClient = null;

let subscriber = null;
let connection: Promise<any>;
let connectedPromise: any = null;
let listener: Observable<any>;
let listenerObserver: any;
let alreadyConnectedOnce = false;

const createConnection = (): Promise<any> => new Promise((resolve) => (connectedPromise = resolve));

const createListener = (): Observable<any> =>
  new Observable(observer => {
    listenerObserver = observer;
  });

export const sendActivity = (page: string) => {
  connection?.then(() => {
    stompClient?.send(
      '/topic/activity', // destination
      JSON.stringify({ page }), // body
      {} // header
    );
  });
};

const subscribe = () => {
  connection.then(() => {
    subscriber = stompClient.subscribe('/topic/tracker', data => {
      listenerObserver.next(JSON.parse(data.body));
    });
  });
};

const connect = () => {
  if (connectedPromise !== null || alreadyConnectedOnce) {
    // the connection is already being established
    return;
  }
  connection = createConnection();
  listener = createListener();

  // building absolute path so that websocket doesn't fail when deploying with a context path
  const loc = window.location;
  const baseHref = document.querySelector('base').getAttribute('href').replace(/\/$/, '');

  const headers = {};
<%_ if (authenticationTypeSession) { _%>
  const url = '//' + loc.host + baseHref + '/websocket/tracker';
  headers['X-XSRF-TOKEN'] = cookie.read('XSRF-TOKEN');
<%_ } else { _%>
  let url = '//' + loc.host + baseHref + '/websocket/tracker';
  const authToken = Storage.local.get('<%= jhiPrefixDashed %>-authenticationToken') || Storage.session.get('<%= jhiPrefixDashed %>-authenticationToken');
  if (authToken) {
    url += '?access_token=' + authToken;
  }
<%_ } _%>
  const socket = new SockJS(url);
  stompClient = Stomp.over(socket, { protocols: ['v12.stomp'] });

  stompClient.connect(headers, () => {
    connectedPromise('success');
    connectedPromise = null;
    sendActivity(window.location.pathname);
    alreadyConnectedOnce = true;
  });
};

const disconnect = () => {
  if (stompClient !== null) {
    if (stompClient.connected) {
      stompClient.disconnect();
    }
    stompClient = null;
  }
  alreadyConnectedOnce = false;
};

const receive = () => listener;

const unsubscribe = () => {
  if (subscriber !== null) {
    subscriber.unsubscribe();
  }
  listener = createListener();
};

export default store => next => action => {
  if (getAccount.fulfilled.match(action)) {
    connect();
    const isAdmin = action.payload.data.authorities.includes('ROLE_ADMIN');
    if (!alreadyConnectedOnce && isAdmin) {
      subscribe();
      receive().subscribe(activity => {
        return store.dispatch(websocketActivityMessage(activity));
      });
    }
  } else if (getAccount.rejected.match(action) || <% if (authenticationTypeJwt) { %>action.type === logoutSession().type<% } else { %>logoutServer.pending.match(action)<% } %>) {
    unsubscribe();
    disconnect();
  }
  return next(action);
};
